//获取路径携带的信息
var loc = location.href,
    n1 = loc.length,//地址的总长度
    n2 = loc.indexOf('='),//取得=号的位置
    id = decodeURI(loc.substr(n2 + 1, n1 - n2));

var $;

layui.use(['jquery', 'form'], function () {
    $ = layui.jquery;
    var form = layui.form;

    $.ajax({
        url: '/User/getById',
        type: 'post',
        dataType: 'json',
        data: {'id': id},
        success: function (item) {
            $('#trueName').text(item.data.trueName);
            $('#id').text(item.data.userId);
            $('textarea[name=remark]').val(item.data.remark);
        }
    });

    //查询所有权限类型
    $.ajax({
        url: '/UserAuthority/getAllAuthority',
        type: 'post',
        dataType: 'json',
        success: function (item) {
            var el = $('<form class="layui-form"></form>')
            item.data.forEach(function (authority) {
                if (authority.trId == 1){
                    el.append('<input type="checkbox" lay-filter="check" name="'+authority.trId+'" lay-skin="primary" title="'+authority.trName+'" disabled/>');
                }else{
                    el.append('<input type="checkbox" lay-filter="check" name="'+authority.trId+'" lay-skin="primary" title="'+authority.trName+'">');
                }
            });

            $('#check').append(el);
            form.render();
        }
    });

    //选中当前用户的权限
    $.ajax({
        url: '/UserAuthority/getByUserId',
        type: 'post',
        dataType: 'json',
        data: {'id': id},
        success: function (item) {
            if (item.data != null) {
                item.data.forEach(function (id) {
                    $('input[name='+id+']').attr('checked', 'checked');
                    form.render();
                });
            }
        }
    });

    //添加权限
    form.on('checkbox(check)', function (data) {
        console.log(data.elem); //得到checkbox原始DOM对象
        var checked = data.elem.checked;
        if (checked){
            $.ajax({
                url: '/UserAuthority/addUserAuthority',
                type: 'post',
                dataType: 'json',
                data: {
                    'userId': id,
                    'authorityId': data.elem.name
                },
                success: function (item) {
                }
            });
        } else {
            $.ajax({
                url: '/UserAuthority/DeleteUserAuthority',
                type: 'post',
                dataType: 'json',
                data: {
                    'userId': id,
                    'authorityId': data.elem.name
                },
                success: function (item) {
                }
            });
        }
    });

    form.render();
});
